package com.example.k8s.hello.service.common.http;

import cn.dev33.satoken.error.SaErrorCode;
import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * 处理接口调用的权限控制
 */
@Slf4j
public class RestClientInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 打印日志
        //TO-DO

        ClientHttpResponse response = execution.execute(request, body);

        if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(401))) {
            log.info("url[{}]返回401，token[{}]已失效", request.getURI(), StpUtil.getTokenValue());
            throw new SaTokenException(SaErrorCode.CODE_11012);
        }
        if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(403))) {
            log.info("url[{}]返回403，权限不足", request.getURI());
            throw new SaTokenException(SaErrorCode.CODE_11051);
        }
        return response;
    }
}
